package cn.me.alphamq.broker.model.consumequeue;

import cn.me.alphamq.broker.util.ByteConvertUtil;

/**
 * ConsumeQueue 索引的模型
 *
 * @author f
 */
public class ConsumeQueueIndexModel {

    /**
     * 消息所在的文件名称，由于文件名是一个 8 位的数字，所以可以将其作为整形保存
     */
    private int commitLogFileName;

    /**
     * 消息数据起始的偏移量
     */
    private int msgOffset;

    /**
     * 消息长度
     */
    private int msgLength;

    /**
     * 消息重试次数
     */
    private int retryTimes;

    public ConsumeQueueIndexModel() {
    }

    public ConsumeQueueIndexModel(byte[] data) {
        this.commitLogFileName = ByteConvertUtil.rangeBytesToInt(data, 0);
        this.msgOffset = ByteConvertUtil.rangeBytesToInt(data, 4);
        this.msgLength = ByteConvertUtil.rangeBytesToInt(data, 8);
        this.retryTimes = ByteConvertUtil.rangeBytesToInt(data, 12);
    }

    /**
     * 将本对象转换成 byte 数组
     *
     * @return byte 数组
     */
    public byte[] toBytes() {
        byte[] commitLogFileNameBytes = ByteConvertUtil.intToBytes(commitLogFileName);
        byte[] msgOffsetBytes = ByteConvertUtil.intToBytes(msgOffset);
        byte[] msgLengthBytes = ByteConvertUtil.intToBytes(msgLength);
        byte[] retryTimesBytes = ByteConvertUtil.intToBytes(retryTimes);
        // 4 个 int 大小是 16 字节
        byte[] res = new byte[16];
        int k = 0;
        for (byte commitLogFileNameByte : commitLogFileNameBytes) {
            res[k++] = commitLogFileNameByte;
        }
        for (byte msgOffsetByte : msgOffsetBytes) {
            res[k++] = msgOffsetByte;
        }
        for (byte msgLengthByte : msgLengthBytes) {
            res[k++] = msgLengthByte;
        }
        for (byte retryTimesByte : retryTimesBytes) {
            res[k++] = retryTimesByte;
        }
        return res;
    }

    public int getCommitLogFileName() {
        return commitLogFileName;
    }

    public void setCommitLogFileName(int commitLogFileName) {
        this.commitLogFileName = commitLogFileName;
    }

    public int getMsgOffset() {
        return msgOffset;
    }

    public void setMsgOffset(int msgOffset) {
        this.msgOffset = msgOffset;
    }

    public int getMsgLength() {
        return msgLength;
    }

    public void setMsgLength(int msgLength) {
        this.msgLength = msgLength;
    }

    public int getRetryTimes() {
        return retryTimes;
    }

    public void setRetryTimes(int retryTimes) {
        this.retryTimes = retryTimes;
    }

    @Override
    public String toString() {
        return "ConsumeQueueIndexModel{" +
               "commitLogFileName=" + commitLogFileName +
               ", msgOffset=" + msgOffset +
               ", msgLength=" + msgLength +
               ", retryTimes=" + retryTimes +
               '}';
    }
}
